// import { doRegister } from './index';
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import * as services from "services/user";
import { createSelector } from "reselect";
import { addBuilder } from "../dict";

import type { RegisterData } from "services/user";
// import type { RegisterData } from "services/user";

export const doGetUserList = createAsyncThunk<any>(
  "user/doGetUserList",
  async () => {
    const res = await services.doGetUserList();
    return res;
  }
);

export const doSendEmailCode = createAsyncThunk<any, string>(
  "user/doSendEmailCode",
  async (email) => {
    const res = await services.doSendEmailCode(email);
    return res;
  }
);

export const doRegister = createAsyncThunk<any, RegisterData>(
  "user/doRegister",
  async (data) => {
    const res = await services.doRegister(data);
    return res;
  }
);
// export const doRegister = createAsyncThunk<any, RegisterData>(
//   "user/doRegister",
//   async (data) => {
//     const res = await services.doRegister(data);
//     return res;
//   }
// );

// export const doRegister = createAsyncThunk<any, RegisterData>(
//   "user/doRegister",
//   async (data) => {
//     const res = await services.doRegister(data);
//     return res;
//   }
// );

type UserState = {
  list: { name: string; age: number; email: string }[];
  count: number;
  loading?: boolean;
};

//创建初始化 state
const initialState: UserState = {
  list: [],
  count: 0,
  loading: false,
};

//创建切片 slice
const UserSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    add(state, action: { type: string; payload?: any }) {
      if (action.payload) {
        state.count += action.payload;
      } else {
        state.count++;
      }
    },
    del(state, action: { type: string; payload?: any }) {
      state.count--;
    },
  },
  extraReducers: (builder) => {
    // //pendding,fullfiled,rejected
    // builder
    //   .addCase(doGetUserList.pending, (state, action) => {
    //     state.loading = true;
    //   })
    //   .addCase(doGetUserList.fulfilled, (state, action) => {
    //     console.log(state, action);
    //     state.loading = false;
    //     state.list = action.payload;
    //   })
    //   .addCase(doGetUserList.rejected, (state, action) => {
    //     state.loading = false;
    //     console.log(state, action.error?.message);
    //   });

    addBuilder(builder, doGetUserList, (state, action) => {
      console.log(action);
      //fulfilled
      if (action.error?.message) {
        alert(action.error.message);
        return;
      }
      state.list = action.payload;
      //
    });
    addBuilder(builder, doSendEmailCode, (state, action) => {
      console.log(action);
    });
  },
});

export const { add, del } = UserSlice.actions;

export const userSelect = (state: any) => state.user;
export const userListSelect = createSelector(userSelect, (user) => user.list);

export default UserSlice.reducer;

//findDiseaseKnowledge
